<template>
  <div>
  <el-dialog
    :title="!dataForm.populationCoding ? $t('handle.add') : btnshow ? '修改':'详情'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-row>
        <el-col :span="12">
      <el-form-item label="人像" style="height:60px;">
       <el-upload
        class="avatar-uploader"
        action="/clientauth/client/upload"
        :show-file-list="false"
        :on-success="handleSucess"
        :before-upload="beforeAvatarUpload"
        :disabled="isInput"
        :headers="headers">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" style="border-radius:30px;">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
      </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="managementCategory">
              <el-select v-model="dataForm.managementCategory" :disabled="isInput" filterable  placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in rklbOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
             </el-form-item>
          </el-col>
      </el-row>
    <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('form.name')" prop="name">
            <el-input v-model="dataForm.name" :disabled="isInput" placeholder="姓名"></el-input>
          </el-form-item>
        </el-col>
          <el-col :span="12">
        <el-form-item label="身份证" prop="identityNumber">
           <!-- @blur="inputBlur()" -->
          <el-input v-model="dataForm.identityNumber" :disabled="isInput" placeholder="身份证号"></el-input>
        </el-form-item>
        </el-col>
    </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="证件种类" prop="identificationType">
        <el-select v-model="dataForm.identificationType" filterable :disabled="isInput"  placeholder="请选择" style="width:100%">
        <el-option
          v-for="item in zjlxOptions"
          :key="item.id"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      </el-form-item>
      </el-col>
          <el-col :span="12">
      <el-form-item label="证件号" prop="identificationNumber">
        <el-input v-model="dataForm.identificationNumber" :disabled="isInput" placeholder="证件号码"  ></el-input>
      </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="房屋"  prop="addressName" v-show="false">
          <el-input :disabled="true" v-model="houseAndPopulation.addressName" placeholder="实有房屋" style="width:80%"></el-input><el-button type="info" plain :disabled="isInput"  @click="buttonHouseHandle()">选择</el-button>
        </el-form-item>
      </el-col>
        <el-col :span="12">
          <el-form-item label="关系"  prop="type" v-show="false">
            <el-select v-model="dataForm.type" :disabled="isInput" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
          </el-select>
          </el-form-item>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="12">
          <el-form-item label="单位"  prop="unitIdText">
            <el-input :disabled="true" v-model="dataForm.unitIdText" placeholder="实有单位" style="width:80%"></el-input><el-button type="info" plain :disabled="isInput"  @click="buttonHandle()">选择</el-button>
          </el-form-item>
         </el-col>
          <el-col :span="12">
      <el-form-item label="曾用名">
        <el-input v-model="dataForm.usedName" :disabled="isInput" placeholder="曾用名"></el-input>
      </el-form-item>
      </el-col>
    </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="外文姓" >
        <el-input v-model="dataForm.foreignSurname" :disabled="isInput" placeholder="外文姓"></el-input>
      </el-form-item>
      </el-col>
          <el-col :span="12">
      <el-form-item label="外文名" >
        <el-input v-model="dataForm.foreignName" :disabled="isInput" placeholder="外文名"></el-input>
      </el-form-item>
      </el-col>
    </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item :label="$t('form.sex')" prop="sex">
        <el-select v-model="dataForm.sex" :disabled="true"  placeholder="请选择" style="width:100%">
        <el-option
          v-for="item in sexOptions"
          :key="item.id"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      </el-form-item>
      </el-col>
          <el-col :span="12">
      <el-form-item label="民族" prop="nation">
        <el-select v-model="dataForm.nation" :disabled="isInput" filterable  placeholder="请选择" style="width:100%">
        <el-option
          v-for="item in nationOptions"
          :key="item.id"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      </el-form-item>
      </el-col>
    </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item :label="$t('form.birthDate')" prop="birthdate">
        <el-input v-model="dataForm.birthdate" :disabled="true" placeholder="出生日期"></el-input>
      </el-form-item>
      </el-col>
          <el-col :span="12">
      <el-form-item label="注销类别" prop="logoutCategory">
        <el-select v-model="dataForm.logoutCategory" filterable :disabled="isInput"  placeholder="请选择" style="width:100%">
        <el-option
          v-for="item in rkzxlbOptions"
          :key="item.id"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      </el-form-item>
          </el-col>
      </el-row>

      <el-form-item
            v-for="(domain,index) in house_populationList.domains"
            label="实有房屋"
            :key="domain.key"
      >
        <el-input v-model="domain.addressName" placeholder="选择房屋" style="width:55%;margin-right:5px;" :disabled="true" ></el-input>
          <!-- <el-tooltip class="item" effect="dark" content="选择人员" placement="top" style="margin-right:5px;"> -->
               <el-button type="success" v-show="btnshow" icon="el-icon-check" circle @click="buttonHouseHandle(index,domain.houseId)"></el-button>
          <!-- </el-tooltip> -->
          <el-select v-model="domain.dictValue" :disabled="isInput" placeholder="请选择" style="margin-right:5px;">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-tooltip class="item" effect="dark" content="添加人员框" placement="top" > -->
            <el-button type="primary" v-show="btnshow" icon="el-icon-plus" @click="addDomain" circle></el-button>
          <!-- </el-tooltip> -->
           <!-- <el-tooltip class="item" effect="dark" content="删除人员框" placement="top"> -->
            <el-button type="danger" v-show="btnshow" icon="el-icon-minus" @click.prevent="removeDomain(domain)" circle></el-button>
          <!-- </el-tooltip> -->
       </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
      <el-button type="primary" v-show="btnshow" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>
  </el-dialog>
  <actuaunit-Dialog v-if="addOrUpdateVisible" ref="actuaunitDialog" @receiveParameters="getParameters"></actuaunit-Dialog>
  <house-Dialog v-if="houseVisible" ref="houseDialog" @receiveParameters="getHouseParameters"></house-Dialog>
  </div>
</template>

<script>
import { getDictList, getUnitMessage, getPhotoUrl, existIdCard } from "@/utils";
import ActuaunitDialog from "../dialog/actuaunitDialog";
import HouseDialog from "../dialog/houseDialogMore";
import Vue from "vue";
import { imgUrlHost } from '@/config/env'
export default {
  data() {
    let checkIdcard = (rule, value, callback) => {
      if (!this.validateIdCard(value)) {
        this.dataForm.sex = "";
        this.dataForm.birthdate = "";
        return callback(new Error("身份证号格式错误，请检查输入"));
      } else {
        existIdCard(value, this.dataForm.populationCoding).then(({ data }) => {
          if (data.count > 0) {
            return callback(new Error("身份证号码已经存在"));
          } else {
            this.dataForm.sex = this.getSexByIdCard(value);
            this.dataForm.birthdate = this.getBirthday(value);
            return callback();
          }
        });
      }
    };
    return {
      visible: false,
      isInput: false,
      headers: {
        Authorization: "Bearer " + Vue.cookie.get("access-token")
        // Authorization: 'Bearer pp'
      },
      imageUrl: "../../../static/img/photo.png",
      btnshow: true,
      houseVisible: false,
      imgUrlHost:imgUrlHost,
      dataForm: {
        populationCoding: "",
        managementCategory: "",
        identityNumber: "",
        name: "",
        usedName: "",
        identificationType: "",
        identificationNumber: "",
        foreignSurname: "",
        foreignName: "",
        sex: "",
        nation: "",
        birthdate: "",
        logoutCategory: "",
        unitId: "",
        unitIdText: "",
        type: "",
        addressName: "",
        addressId: "",
        portraitId: ""
      },
      dataRule: {
        managementCategory: [
          {
            required: true,
            message: "实有人口管理类别不能为空",
            trigger: "blur"
          }
        ],
        identityNumber: [
          { validator: checkIdcard, required: true, trigger: "blur" }
        ],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        identificationType: [
          { required: true, message: "证件种类不能为空", trigger: "blur" }
        ],
        identificationNumber: [
          { required: true, message: "证件号码不能为空", trigger: "blur" }
        ],
        // houseName: [
        //   { required: true, message: '房屋不能为空', trigger: 'blur' }
        // ],
        // type: [
        //   { required: true, message: '人房关系不能为空', trigger: 'blur' }
        // ],
        unitIdText1: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ]
        // sex: [
        //   { required: true, message: '性别不能为空', trigger: 'blur' }
        // ],
        // nation: [
        //   { required: true, message: '民族不能为空', trigger: 'blur' }
        // ],
        // birthdate: [
        //   { required: true, message: '出生日期不能为空', trigger: 'blur' }
        // ],
        // logoutCategory: [
        //   { required: true, message: '人口注销类别不能为空', trigger: 'blur' }
        // ],
        // unitIdText: [
        //   { required: true, message: '实有单位id不能为空', trigger: 'blur' }
        // ]
        // addressId: [
        //   { required: true, message: '标准地址id不能为空', trigger: 'blur' }
        // ],
        // portraitId: [
        //   { required: true, message: '标准人像id不能为空', trigger: 'blur' }
        // ]
      },
      nationOptions: [],
      sexOptions: [],
      zjlxOptions: [],
      options: [],
      rklbOptions: [],
      addOrUpdateVisible: false,
      rkzxlbOptions: [],
      houseAndPopulation: {
        houseId: "",
        addressName: "",
        dictValue: ""
      },
      house_populationList: {
        domains: [
          {
            houseId: "",
            addressName: "",
            dictValue: ""
          }
        ]
      }
    };
  },
  components: {
    "actuaunit-Dialog": ActuaunitDialog,
    "house-Dialog": HouseDialog
  },
  computed: {
    addressId() {
      return this.$store.state.address.id;
    }
  },
  methods: {
    addDomain() {
      this.house_populationList.domains.push({
        houseId: "",
        addressName: "",
        dictValue: ""
      });
    },
    removeDomain(item) {
      var index = this.house_populationList.domains.indexOf(item);
      if (index !== 0) {
        this.house_populationList.domains.splice(index, 1);
      }
    },
    reset() {
      getDictList("type").then(({ data }) => {
        if (data && data.code === 0) {
          this.options = data.dictList;
        }
      });
      this.dataForm.usedName = "";
      this.dataForm.foreignSurname = "";
      this.dataForm.foreignName = "";
      this.dataForm.sex = "";
      this.dataForm.nation = "";
      this.dataForm.birthdate = "";
      this.dataForm.logoutCategory = "";
      this.dataForm.unitId = "";
      this.dataForm.portraitId = "";
    },
    init(id, detail) {
      this.reset();
      this.btnshow = true;
      this.isInput = false;
      this.getSelectData();
      this.dataForm.populationCoding = id || 0;
      this.visible = true;
      if (detail) {
        this.btnshow = false;
        this.isInput = true;
      }
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.imageUrl = "../../../static/img/photo.png";
        if (this.dataForm.populationCoding) {
          this.$http({
            // url: this.$http.adornUrl(`/dgactualpopulation/info/${this.dataForm.populationCoding}`),
            url: `/dg-standard-info/dgactualpopulation/info/${this.dataForm.populationCoding}`,
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.unitIdText = "";
              this.dataForm.managementCategory =
                data.dgActualPopulation.managementCategory;
              this.dataForm.identityNumber =
                data.dgActualPopulation.identityNumber;
              this.dataForm.name = data.dgActualPopulation.name;
              this.dataForm.usedName = data.dgActualPopulation.usedName;
              this.dataForm.identificationType =
                data.dgActualPopulation.identificationType;
              this.dataForm.identificationNumber =
                data.dgActualPopulation.identificationNumber;
              this.dataForm.foreignSurname =
                data.dgActualPopulation.foreignSurname;
              this.dataForm.foreignName = data.dgActualPopulation.foreignName;
              this.dataForm.sex = data.dgActualPopulation.sex;
              this.dataForm.nation = data.dgActualPopulation.nation;
              this.dataForm.birthdate = data.dgActualPopulation.birthdate;
              this.dataForm.logoutCategory =
                data.dgActualPopulation.logoutCategory;
              if (data.dgActualPopulation.houseAdreessVo === null) {
                this.house_populationList.domains = {
                  domains: [
                    {
                      houseId: "",
                      addressName: "",
                      dictValue: ""
                    }
                  ]
                };
              } else {
                this.house_populationList.domains =
                  data.dgActualPopulation.houseAdreessVo;
              }
              if (data.dgActualPopulation.unitEntity !== null) {
                this.dataForm.unitId = data.dgActualPopulation.unitEntity.unitCode;
                this.dataForm.unitIdText = data.dgActualPopulation.unitEntity.name;
              }
              // getUnitMessage(data.dgActualPopulation.unitId).then(({data}) => {
              //   if(data.dgActualUnit){
              //     this.dataForm.unitIdText = data.dgActualUnit.name
              //   }
              // })
              // this.dataForm.addressId = data.dgActualPopulation.addressId
              if (data.dgActualPopulation.portraitEntity !== null) {
                this.dataForm.portraitId =
                  data.dgActualPopulation.portraitEntity.id;
              }
              this.imageUrl = this.getPhoto(data.dgActualPopulation.portraitEntity);
              // getPhotoUrl(data.dgActualPopulation.portraitId).then(({data}) => {
              //   if(data.dgBasicPortrait){
              //     this.imageUrl = data.dgBasicPortrait.photoUrl
              //   }
              // })
            }
          });
        }
      });
    },
    getPhoto(data) {
      let photo = "";
      if (data === null) {
        photo = "../../../static/img/photo.png";
      } else {
        if (data.photoUrl !== null) {
          photo = this.imgUrlHost + data.photoUrl;
        } else if (data.photoBase64 !== null) {
          photo = "data:image/png;base64," + data.photoBase64;
        } else {
          photo = "../../../static/img/photo.png";
        }
      }
      return photo;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.houseAndPopulation.type = this.dataForm.type;
          this.$http({
            // url: this.$http.adornUrl(`/dgactualpopulation/${!this.dataForm.populationCoding ? 'save' : 'update'}`),
            url: `/dg-standard-info/dgactualpopulation/${
                !this.dataForm.populationCoding ? "save" : "update"
              }`,
            method: "post",
            data: this.$http.adornData({
              populationCoding: this.dataForm.populationCoding || undefined,
              managementCategory: this.dataForm.managementCategory,
              identityNumber: this.dataForm.identityNumber,
              name: this.dataForm.name,
              usedName: this.dataForm.usedName,
              identificationType: this.dataForm.identificationType,
              identificationNumber: this.dataForm.identificationNumber,
              foreignSurname: this.dataForm.foreignSurname,
              foreignName: this.dataForm.foreignName,
              sex: this.dataForm.sex,
              nation: this.dataForm.nation,
              birthdate: this.dataForm.birthdate,
              logoutCategory: this.dataForm.logoutCategory,
              unitId: this.dataForm.unitId,
              // 'addressId': this.addressId,
              houseAndPopulation: this.house_populationList.domains,
              portraitId: this.dataForm.portraitId,
              sysCreateBy: this.$store.state.user.id,
              sysUpdateBy: this.$store.state.user.id
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    buttonHandle() {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.actuaunitDialog.init();
      });
    },
    buttonHouseHandle(index, houseId) {
      this.houseVisible = true;
      this.$nextTick(() => {
        this.$refs.houseDialog.init(index, houseId);
      });
    },
    getParameters(data) {
      this.dataForm.unitId = data.selectId;
      this.dataForm.unitIdText = data.selectText;
    },
    getHouseParameters(data, index) {
      // this.houseAndPopulation.houseId = data.selectId
      // this.houseAndPopulation.houseName = data.selectText
      // this.dataForm.houseName = data.selectText
      this.house_populationList.domains[index].houseId = data.selectId;
      this.house_populationList.domains[index].addressName = data.selectText;
    },
    getSelectData() {
      getDictList("nation").then(({ data }) => {
        this.nationOptions = data.dictList;
      });
      getDictList("sex").then(({ data }) => {
        this.sexOptions = data.dictList;
      });
      getDictList("type_document").then(({ data }) => {
        this.zjlxOptions = data.dictList;
      });
      getDictList("population_type").then(({ data }) => {
        this.rklbOptions = data.dictList;
      });
      getDictList("population_cancellation_type").then(({ data }) => {
        this.rkzxlbOptions = data.dictList;
      });
    },
    getBirthday(idCard) {
      let birthday = "";
      if (idCard !== null && idCard !== "") {
        if (idCard.length === 15) {
          birthday = "19" + idCard.substr(6, 6);
        } else if (idCard.length === 18) {
          birthday = idCard.substr(6, 8);
        }
        birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
      }
      return birthday;
    },
    getSexByIdCard(idCard) {
      if (parseInt(idCard.substr(16, 1)) % 2 === 1) {
        // 男
        return "1";
      } else {
        // 女
        return "2";
      }
    },
    inputBlur() {
      if (this.validateIdCard(this.dataForm.identityNumber)) {
        this.dataForm.sex = this.getSexByIdCard(this.dataForm.identityNumber);
        this.dataForm.birthdate = this.getBirthday(
          this.dataForm.identityNumber
        );
      } else {
      }
    },
    validateIdCard(id, backInfo) {
      let info = {
        y: "1900",
        m: "01",
        d: "01",
        sex: "male",
        valid: false,
        length: 0
      };
      if (typeof id !== "string") return this.back(info, backInfo);
      // 18
      if (/^\d{17}[0-9x]$/i.test(id)) {
        if (!this.initDate(18, info, id)) return this.back(info, backInfo);
        id = id.toLowerCase().split("");
        let wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        let y = "10x98765432".split("");
        let sum = 0;
        for (let i = 0; i < 17; i++) sum += wi[i] * id[i];
        if (y[sum % 11] === id.pop().toLowerCase()) info.valid = true;
        return this.back(info, backInfo);
      } else if (/^\d{15}$/.test(id)) {
        // 15
        if (this.initDate(15, info, id)) info.valid = true;
        return this.back(info, backInfo);
      } else {
        return this.back(info, backInfo);
      }
    },
    back(info, backInfo) {
      return backInfo ? info : info.valid;
    },
    initDate(length, info, id) {
      info.length = length;
      let a;
      a = length === 15 ? 0 : 2; // 15:18
      let temp;
      info.y = (a ? "" : "19") + id.substring(6, 8 + a);
      info.m = id.substring(8 + a, 10 + a);
      info.d = id.substring(10 + a, 12 + a);
      info.sex = id.substring(14, 15 + a) % 2 === 0 ? "female" : "male";
      temp = new Date(info.y, info.m - 1, info.d);
      return (
        temp.getFullYear() === info.y * 1 &&
        temp.getMonth() + 1 === info.m * 1 &&
        temp.getDate() === info.d * 1
      );
    },
    // 文件上传成功时调用
    handleSucess(response, file, fileList) {
      this.$message({
        message: "文件上传成功",
        type: "success",
        duration: 1500,
        onClose: () => {
          this.imageUrl = this.imgUrlHost + response.iconName;
          this.dataForm.portraitId = response.iconName;
          // this.picJson.url = this.dataForm.picUrl
          // this.fileList[0] = this.picJson
        }
      });
    },
    // 文件上传失败时调用
    handleError(file, fileList) {
      this.$message.error("文件上传失败");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      let fileFlag = false;
      if (isJPG || isPNG) {
        fileFlag = true;
      } else {
        this.$message.error("上传头像图片只能是 JPG 格式或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      // * ***************************
      // const isSize = new Promise(function (resolve, reject) {
      //   let width = 500 // 限制图片尺寸为654X270
      //   let height = 500
      //   let _URL = window.URL || window.webkitURL
      //   let img = new Image()
      //   img.onload = function () {
      //     let valid = img.width === width && img.height === height
      //     valid ? resolve() : reject(new Error(0))
      //   }
      //   img.src = _URL.createObjectURL(file)
      // }).then(() => {
      //   return file
      // }, () => {
      //   this.$message.error('图片尺寸限制为500 x 500')
      //   return Promise.reject(new Error(0))
      // })
      return fileFlag && isLt2M; // && isSize
    }
  }
};
</script>

<style>
.el-input.is-disabled .el-input__inner {
  color: #606266;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 64px;
  height: 64px;
  text-align: center;
}
.avatar {
  width: 64px;
  height: 64px;
  display: block;
}
.custom-3E8EF7 .el-form-item.is-required .el-form-item__label:before {
  font-size: 22px;
}
.custom-3E8EF7 .el-input.is-disabled .el-input__inner {
  color: #00000088;
}
</style>

